package com.iqiju.guagua.photo.wx.mini.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iqiju.guagua.photo.wx.mini.common.Results;
import com.iqiju.guagua.photo.wx.mini.mapper.WxMiniFirstPageMapper;
import com.iqiju.guagua.photo.wx.mini.model.WxMiniApp;
import com.iqiju.guagua.photo.wx.mini.model.WxMiniFirstPage;
import com.iqiju.guagua.photo.wx.mini.vo.FirstPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WxMiniFirstPageService extends ServiceImpl<WxMiniFirstPageMapper, WxMiniFirstPage> {

    @Autowired
    private WxMiniAppService wxMiniAppService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public Results<List<FirstPageVO>> selectFirstPageList(String wxMiniAppId) {
        if (wxMiniAppId==null||wxMiniAppId.trim().length()<=0){
            log.error("参数 wxMiniAppId 为空！");
            return Results.paramError("参数 wxMiniAppId 不能为空");
        }
        WxMiniApp wxMiniApp = wxMiniAppService.selectById(Long.parseLong(wxMiniAppId));
        if (wxMiniApp == null){
            log.error("小程序id {} 不存在！", wxMiniAppId);
            return Results.paramError("小程序id "+wxMiniAppId+" 不存在");
        }

        String firstPageValue = stringRedisTemplate.opsForValue().get(getFirstPageKey(wxMiniAppId));
        if (firstPageValue!=null&&firstPageValue.trim().length()>0){
            List<FirstPageVO> firstPageArray = JSON.parseArray(firstPageValue, FirstPageVO.class);
            log.info("从缓存中查询到首页配置数据");
            return new Results(Results.SUCCESS_CODE,Results.SUCCESS_MSG,firstPageArray);
        }

        List<FirstPageVO> firstPageVOS = baseMapper.selectFirstPageList(Long.valueOf(wxMiniAppId));
        if (firstPageVOS.isEmpty()){
            log.error("此小程序[{}]没有配置首页链接", wxMiniAppId);
            return Results.paramError("此小程序["+wxMiniAppId+"]没有配置首页链接");
        }

        /* 根据有没有广告，修改标识 */
        for (int i = 0; i < firstPageVOS.size(); i++) {
            if(firstPageVOS.get(i).getAdList().isEmpty()){
                firstPageVOS.get(i).setHaveAd(0);
            }else{
                firstPageVOS.get(i).setHaveAd(1);
            }
        }
        stringRedisTemplate.opsForValue().set(getFirstPageKey(wxMiniAppId), JSON.toJSONString(firstPageVOS),30, TimeUnit.DAYS);

        return new Results<>(Results.SUCCESS_CODE,Results.SUCCESS_MSG,firstPageVOS);
    }


    private String getFirstPageKey(String wxMiniAppId){
        return "GUAGUA_PHOTO_FIRST_PAGE_LIST_"+wxMiniAppId;
    }

}
